<?php
abstract class CValidator {
	
	/**
	 * @var array list of attributes to be validated.
	 */
	public $attributes;
	
	/**
	 * @var string the user-defined error message. Different validators may define various
	 * placeholders in the message that are to be replaced with actual values. All validators
	 * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
	 */
	public $message;
	
	public static $builtInValidators = array(
		'require' => 'CRequiredValidator',
		'email'=>'CEmailValidator',
	);
	
	abstract protected function validateAttribute($object,$attribute,$value);
	
	public static function createValidator($name, $object, $attributes, $params = array()){
		if(is_string($attributes)){
			$attributes = preg_split('/[\s,]+/', $attributes,-1,PREG_SPLIT_NO_EMPTY);
		}
		$params['attributes'] = $attributes;
		if(isset(self::$builtInValidators[$name])){
			$validator = new self::$builtInValidators[$name];
			foreach ($params as $name => $value) {
				$validator->$name = $value;
			}
			return $validator;
		}		
	}
	
	public function validate($object,$attributes=null,$value){
		$attributes = $this->attributes;
		foreach ($attributes as $attribute) {
			$this->validateAttribute($object,$attribute,$value);
		}		
	}
	
	public function isEmpty($value,$trim=false){
		return $value ===null || $value ===array() || $value ==='' || $trim && is_scalar($value) && trim($value) === '';
	}
	
	public function addError($object,$attribute,$message){
		$object->addError($attribute,$message);
	}
}